<template>
  <div v-loading="loading">
    <b-table
      ref="table"
      :columns="columns"
      :scroll="{ x: 1300 }"
      :request="loadData"
      :export-config="{ use: true,select: '物资结算明细',all: '物资结算明细'}"
    >
      <template
        v-if="state !== 3"
        slot="prefix"
        slot-scope="ref"
      >
        <a-button
          type="primary"
          @click="openDailog"
        >
          添加行
        </a-button>
        <a-button @click="ref.delete(delFunc)">
          删除行
        </a-button>
        <!--<ExcelImportButton @handleSubmit="importFunc"></ExcelImportButton>-->
      </template>
      <template
        v-if="state !== 3"
        slot="suffix"
      >
        <export-mould
          style="margin-left: 5px"
          button-text="标准模板下载"
          template-code="物资结算单.xlsx"
          icon="cloud-download"
        />
        <ExcelImportButton
          button-text="批量导入"
          icon="upload"
          @handleSubmit="importFunc"
        />
      </template>
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <div
        v-for="(col, i) in ['leaseNum','priceExTax','taxTypeName','tax','priceWithTax',
                            'settleAmountWithoutTax','settleTax','settleAmountWithTax','receiptDate',
                            'code','remark']"
        :slot="col"
        :key="i"
        slot-scope="text, record, index"
      >
        <!--<template v-if="index === editingIndex">-->
        <template v-if="state !== 3">
          <a-date-picker
            v-if="col === 'receiptDate'"
            v-model="record[col]"
            v-check="col"
            :class="{tableInputBg:col === 'receiptDate'}"
            value-format="YYYY-MM-DD"
            @change="e => handleChange(e,record)"
          />
          <a-select
            v-else-if="col === 'taxTypeName'"
            v-model="record['taxTypeId']"
            v-check="col"
            :class="{tableInputBg:col === 'taxTypeName'}"
            @change="e => handleChange(e, record)"
          >
            <a-select-option
              v-for="item in rateArr"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
          <BaseInput
            v-else-if="col === 'remark' || col === 'code'"
            v-model="record[col]"
            v-check="col"
            :class="{tableInputBg:col === 'code'}"
            @blur="e => handleChange(e.target.value, record)"
          />
          <BaseInputNumber
            v-else-if="col === 'leaseNum'"
            v-model="record[col]"
            v-check="col"
            :class="{tableInputBg:col === 'leaseNum'}"
            :precision="3"
            :disabled="col === 'tax' || col === 'priceWithTax' || col === 'settleAmountWithoutTax'
              || col === 'settleTax' || col === 'settleAmountWithTax'"
            @blur="e => handleChange(e, record)"
          />
          <BaseInputNumber
            v-else-if="col === 'priceExTax' || col === 'priceWithTax'"
            v-model="record[col]"
            v-check="col"
            :class="{tableInputBg:col === 'priceExTax'}"
            :precision="2"
            :disabled="col === 'tax' || col === 'priceWithTax' || col === 'settleAmountWithoutTax'
              || col === 'settleTax' || col === 'settleAmountWithTax'"
            @blur="e => handleChange(e, record)"
          />
          <BaseInputNumber
            v-else
            v-model="record[col]"
            v-check="col"
            :disabled="col === 'tax' || col === 'priceWithTax' || col === 'settleAmountWithoutTax'
              || col === 'settleTax' || col === 'settleAmountWithTax'"
            @blur="e => handleChange(e.target.value, record)"
          />
        </template>
        <template v-else>
          {{ text }}
        </template>
      </div>
      <!--<template slot="operation" slot-scope="text, record, index">-->
      <!--<div class="editable-row-operations">-->
      <!--<span v-if="index === editingIndex">-->
      <!--<a @click="save(record)">保存</a>-->
      <!--<a @click="cancel(record)">取消</a>-->
      <!--</span>-->
      <!--<span v-else>-->
      <!--<a :disabled="editingIndex !== null || state === 3" @click="editingIndex = index">编辑</a>-->
      <!--</span>-->
      <!--</div>-->
      <!--</template>-->
    </b-table>
    <!--<material-list ref="detailDialog" @createList="createList"-->
    <!--:urlFun="materialDialogList" :other-data="{contractId:contractId,settleId:id}"></material-list>-->
    <materialListAndDir
      ref="detailDialog"
      :mode="'single'"
      :api="materialDialogList"
      :request-params="{ contractId:contractId,settleId:id}"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
    materialDetailList,
    materialDetailDel,
    materialDetailAdd,
    materialDialogList,
    materialDetailEdit,
    exportByDetailsMaterial,
    createMaterials
} from '@/api/material/settlement/settlement'
import { columns } from './insideModel'
import { selectOption } from '@/api/material/goods/goods'
import ExportMould from '@/components/ExportMould'
import materialListAndDir from '@/components/materialListAndDir/materialListAndDir'

const data = []
export default {
  components: {
    ExportMould,
    materialListAndDir
  },
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        },
        contractId: {
            type: String
        }
    },
    data() {
        return {
            loading: false,
            columns: columns,
            materialDialogList: materialDialogList,
            rateArr: [],
            rules: {
                leaseNum: { rule: 'required', message: '数量不能为空' },
                priceExTax: { rule: 'required', message: '税前单价不能为空' },
                taxTypeId: { rule: 'required', message: '税率不能为空' },
                receiptDate: { rule: 'required', message: '收料日期不能为空' },
                code: { rule: 'required', message: '收料单编号不能为空' }
            },
            delFunc: materialDetailDel,
            loadData: params => materialDetailList({ ...params, settleId: this.id }),
            editingIndex: null,
            checkKeys: new Map()
        }
    },
    directives: {
        check: {
            inserted(el, binding, vNode) {
                if (vNode.context.rules[binding.value]) {
                    let rule = vNode.context.rules[binding.value]
                    vNode.context.checkKeys.set(binding.value, rule.message)
                }
            }
        }
    },
    mounted: function() {
        if (this.state === 3) {
            this.editingIndex = null
        }
        this.getRate()
    },
    methods: {
        async importFunc(e) {
          let newTable = [],
            newTableTit = [],
            colEmpty =[],
            emptyTip = '',
            noneColArr = []
          e.map((row, num) => {
            let temp = {}
            newTableTit[num] = []
            for (const rowKey in row) {
              newTableTit[num].push(rowKey)
              let column = this.columns.find(columnRow => columnRow.title === rowKey)
              if (column) {
                let dataIndex = column.dataIndex
                temp[dataIndex] = row[rowKey]
              }
            }
            temp.settleId = this.id
            newTable.push(temp)
            //验证未填项
            let col = ['物料名称', '物料编码', '规格型号', '计量单位', '数量', '税率', '收料日期', '收料单编号']
            noneColArr[num] = []
            col.forEach((item, index) => {
              let status = newTableTit[num].includes(item)
              if (!status) {
                noneColArr[num].push(item)
              }
            })
            if (noneColArr[num].length > 0) {
              colEmpty[num] = {
                name: noneColArr[num],
                num: num+1
              }
            }
          })
          if (colEmpty.length > 0) {
            for (let item in colEmpty) {
              emptyTip += '第' + colEmpty[item].num + '行：' + colEmpty[item].name + '\r\n'
            }
            emptyTip = '请完整输入内容：\r\n' + emptyTip
            this.$notification.open({ message: '提示', duration: null, description: () =><pre>{emptyTip}</pre> })
            return false
          }
            try {
              this.loading = true
              let res = await exportByDetailsMaterial(newTable)
              let msg = res.message
              this.loading = false
              this.$refs.table.getData(null, true)
              this.$notification.open({ message: '提示', duration: null, description: () =><pre>{msg}</pre> })
            }catch (e) {
                this.loading = false
              }
        },
        async getRate() {
            let res = await selectOption({ type: 21 })
            if (res.code === 200) {
                this.rateArr = res.data
            }
        },
        openDailog: function() {
            if (this.editingIndex !== null) {
                this.$message.error('新增前请结束当前操作行')
                return
            }
            this.$refs.detailDialog.open()
        },
        createList: function(selectRow) {
          selectRow.map(item => {
            item.settleId= this.id
          })
          this.calcMethodId = null
          this.taxTypeId = null
          createMaterials(selectRow).then(res => {
            if (res.code === 200) {
              // this.cancel()
              this.$refs.table.getData(null, true)
            }
          })
        },
        handleChange(value, target) {
              this.rateArr.map(function(item) {
                if (target.taxTypeId === item.id) {
                    let num = item.name.replace('%', '')
                    num = num / 100
                  target['taxTypeName'] = item.name
                  target['tax'] = target['priceExTax'] * num
                  target['tax'] =   target['tax'].toFixed(2)
                  target['settleTax'] = target['leaseNum'] * target['priceExTax'] * num
                  target['settleTax'] =   target['settleTax'].toFixed(2)
                }
            })
            target['priceWithTax'] = Number(target['priceExTax']) + Number(target['tax'])
          target['priceWithTax'] =   target['priceWithTax'].toFixed(2)
          target['settleAmountWithoutTax'] = target['leaseNum'] * target['priceExTax']
          target['settleAmountWithoutTax'] =   target['settleAmountWithoutTax'].toFixed(2)
          target['settleAmountWithTax'] = Number(target['settleAmountWithoutTax']) + Number(target['settleTax'])
          target['settleAmountWithTax'] =   target['settleAmountWithTax'].toFixed(2)
          this.save(target, 'state')
        },
        async save(row, state) {
          try {
                // this.checkKeys.forEach((value, key) => {
                //     if (this.$isEmpty(row[key])) {
                //         this.$noticeWarning(value)
                //         throw new Error(value)
                //     }
                // })
                if(!state){
                  this.loading = true
                }
                let res = await materialDetailEdit(row)
                if (res.code === this.SUCCESS_CODE) {
                  if(!state){
                    this.$noticeSuccess('编辑成功')
                  }
                    // this.cancel()
                }
            if(!state){
              this.loading = false
              this.$emit('disabledSub', false)
            }
          } catch (e) {
                // this.$noticeWarning(e.message)
            if(!state){
              this.loading = false
              this.$emit('disabledSub', false)
            }
          }
        },
        // cancel() {
        //     this.editingIndex = null
        //     this.$refs.table.getData()
        // }
    }
}
</script>
<style scoped>
  /deep/ .tableInputBg .ant-input-number,
  /deep/ .tableInputBg .ant-calendar-picker-input,
  /deep/ .tableInputBg>input,
  /deep/ .tableInputBg .ant-select-selection{
    background-color: #fff9e8;
    border:1px solid #e4ac0b;
  }
</style>